package cn.hicard.risk.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;

/**
 * 文件压缩工具类
 * @author Administrator
 *
 */
public class Compress {
	
	/** 日志记录工具 */
	private static Logger logger = Logger.getRootLogger();
	
	/**
	 * 将一系列文件ZIP压缩到输出流中
	 * @param files
	 * @param output
	 */
	public static void zip(String[] files, OutputStream output){
		try {
			
			CheckedOutputStream csum = new CheckedOutputStream(output, new CRC32());
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(csum));
						
			for (int i = 0; i < files.length; i++) {
				String file = files[i];
				logger.debug("开始ZIP压缩：" + file + " ... ...");
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
				// 组织ZIP文件目录结构 统一放到一个文件下
				zos.putNextEntry(new ZipEntry(file.substring(file.lastIndexOf("/") + 1)));
				int c;
				while((c = bis.read()) != -1) zos.write(c);
				bis.close();
				logger.debug("完成ZIP压缩：" + file);
			}
			logger.info("所有文件完成压缩，CRC32校验和=" + csum.getChecksum().getValue());
			zos.close();
		} catch (Exception e){
			logger.error("", e);
		}
	}
	
	/**
	 * 将一系列文件ZIP压缩到同一个文件中
	 * @param files
	 * @param zipfile
	 */
	public static void zip(List<String> files, String zipfile){
		try {
			// zip输出文件
			FileOutputStream fos = new FileOutputStream(zipfile);
			CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(csum));
						
			for (int i = 0; i < files.size(); i++) {
				String file = files.get(i);
				logger.debug("开始ZIP压缩：" + file + " ... ...");
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
				// 组织ZIP文件目录结构 统一放到一个文件下
				zos.putNextEntry(new ZipEntry(file.substring(file.lastIndexOf("/") + 1)));
				int c;
				while((c = bis.read()) != -1) zos.write(c);
				bis.close();
				logger.debug("完成ZIP压缩：" + file);
			}
			logger.info(files + "所有文件完成压缩，CRC32校验和=" + csum.getChecksum().getValue());
			zos.close();
		} catch (Exception e){
			logger.error("", e);
		}
	}
	
}
